//
//  MyRotatingButton.cpp
//  CanYouDoIt
//
//  Created by hoangtx on 7/11/13.
//
//

#include "MyRotatingButton.h"
#include "MyUtilities.h"

bool MyRotatingButton::init(){
    MySpriteButton::init();
    currentAngle = M_PI/2;
    angleVelocity = -M_PI/360;
    maxSpeed = M_PI/45;
    originalAngle = currentAngle;
    originalVelocity = angleVelocity;
    return true;
}

MyRotatingButton* MyRotatingButton::create(const char *fileName, double mX, double mY, double mWidth, double mHeight){
    MyRotatingButton* button = MyRotatingButton::create();
    button->setPosition(ccp(mX,mY));
    button->buttonSize = CCSizeMake(mWidth, mHeight);
    button->sprite = CCSprite::create(fileName);
    button->sprite->setAnchorPoint(ccp(0,0));
    button->sprite->setScaleX(mWidth/button->sprite->getContentSize().width);
    button->sprite->setScaleY(mHeight/button->sprite->getContentSize().height);
    button->sprite->setPosition(ccp(0,0));
    button->sprite->setColor(button->normalColor);
    button->addChild(button->sprite);
    button->originalPoint = button->getPosition();
    return button;

}

void MyRotatingButton::setCircle(cocos2d::CCPoint mOrigin, double mRadius){
    originPoint = mOrigin;
    radius = mRadius;
    originalOriginPoint = originPoint;
}

void MyRotatingButton::resetState(){
    MySpriteButton::resetState();
    currentAngle = originalAngle;
    angleVelocity= originalVelocity;
    setPosition(originalPoint);
    originPoint = originalOriginPoint;
}

void MyRotatingButton::randomDirection(){
    int veloRandom = rand()% 2;
    if(veloRandom==0){
        angleVelocity = -angleVelocity;
    }
}

bool MyRotatingButton::isAtMaxSpeed(){
    return MyUtilities::triTuyetDoi(angleVelocity)>=maxSpeed;
}

void MyRotatingButton::increseVelocityBy(double radDegree){

    int sign;
    if(angleVelocity==0){
        sign = 1;
    }else{
        sign = angleVelocity/MyUtilities::triTuyetDoi(angleVelocity);
    }
    if(sign==1){
        angleVelocity += radDegree;
    }else{
        angleVelocity -= radDegree;
    }
}

void MyRotatingButton::changeDirection(){
    angleVelocity = -angleVelocity;
}

void MyRotatingButton::handleUpdate(float dt){
    currentAngle+=angleVelocity;
    CCPoint destinationPoint = MyUtilities::rotateAroundPoint(originPoint, currentAngle, radius);
    this->setPosition(destinationPoint);
}